package com.elitel.common.elasticSearch;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

public class ESPoolUtil {
    private  GenericObjectPool<ESClient> clientPool = null;

    public ESPoolUtil(String address,int port,String clustername,int maxtotal,int minEvictableIdle,int timeBetweenEviction) {
        // 对象池配置类对象
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

        // 设置池中client最大数量
        poolConfig.setMaxTotal(maxtotal);

        //设置池中对象回收的最小的空闲时间
        poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdle);

        //设置池中对象回收线程扫描的时间间隔，为负数则不开启该线程
        poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEviction);

        // 创建ESClientPoolFactory工厂类对象
        ESClientPoolFactory esClientPoolFactory = new ESClientPoolFactory(address,port,clustername);

        //生成对象池
        this.clientPool = new GenericObjectPool<ESClient>(esClientPoolFactory, poolConfig);
    }
    /**
     * 获得对象
     *
     * @return
     */
    public  ESClient getClient() {
        // 从池中获取一个对象
        ESClient client = null;
        try {
            client = clientPool.borrowObject();
        } catch (Exception e) {
            System.out.println("客户端连接池中获取ES客户端失败");
        }
        return client;
    }

    /**
     * 归还对象
     *
     * @param client
     */
    public  void  returnClient(ESClient client) {
        clientPool.returnObject(client);
    }
}
